package zxj.weixin.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HTTP客户端工具类
 * 
 * @author zhuxuejiang
 *
 */
public class HttpClientUtils {

	static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtils.class);

	static final RequestConfig GET_REQUEST_CONFIG = RequestConfig.custom().setSocketTimeout(5000)
			.setConnectTimeout(5000).setConnectionRequestTimeout(5000).build();

	static final RequestConfig POST_REQUEST_CONFIG = RequestConfig.custom().setSocketTimeout(15000)
			.setConnectTimeout(15000).setConnectionRequestTimeout(15000).build();

	/**
	 * 发送GET请求
	 * 
	 * @param url 请求的URL
	 * @return 返回的内容
	 * @throws Exception
	 */
	public static String get(String url) throws Exception {
		HttpGet get = new HttpGet(url);
		get.setConfig(GET_REQUEST_CONFIG);

		return execute(get);
	}

	/**
	 * 发送POST请求
	 * 
	 * @param url 请求的URL
	 * @return 返回的内容
	 * @throws Exception
	 */
	public static String post(String url) throws Exception {
		HttpPost post = new HttpPost(url);
		post.setConfig(POST_REQUEST_CONFIG);

		return execute(post);
	}

	/**
	 * 发送POST请求
	 * 
	 * @param url  请求的URL
	 * @param body 请求的消息体
	 * @return 返回的内容
	 * @throws Exception
	 */
	public static String post(String url, String body) throws Exception {

		StringEntity requestEntity = new StringEntity(body, "utf-8");

		HttpPost post = new HttpPost(url);
		post.setConfig(POST_REQUEST_CONFIG);
		post.addHeader("Content-type", "application/json; charset=utf-8");
		post.setHeader("Accept", "application/json");
		post.setEntity(requestEntity);

		return execute(post);
	}

	/**
	 * 发送POST请求
	 * 
	 * @param url    请求的URL
	 * @param params 请求参数Map
	 * @return 返回的内容
	 * @throws Exception
	 */
	public String post(String url, Map<String, String> params) throws Exception {
		HttpPost post = new HttpPost(url);
		post.setConfig(POST_REQUEST_CONFIG);

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

		for (String key : params.keySet()) {
			nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
		}

		try {
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
		} catch (Exception e) {
			LOGGER.error("发送POST请求错误！", e);
			throw e;
		}
		return execute(post);
	}

	/**
	 * 发送POST请求
	 * 
	 * @param url  请求的URL
	 * @param file 上传文件
	 * @return 返回的内容
	 * @throws Exception
	 */
	public static String post(String url, File file) throws Exception {
		List<File> fileList = new ArrayList<>();
		fileList.add(file);
		return post(url, fileList);
	}

	/**
	 * 发送POST请求
	 * 
	 * @param url  请求的URL
	 * @param file 上传文件
	 * @return 返回的内容
	 * @throws Exception
	 */
	public static String post(String url, List<File> fileList) throws Exception {
		return post(url, null, fileList);
	}

	/**
	 * 发送POST请求
	 * 
	 * @param url      请求的URL
	 * @param params   请求参数Map
	 * @param fileList 上传文件列表
	 * @return 返回的内容
	 * @throws Exception
	 */
	public static String post(String url, Map<String, String> params, List<File> fileList) throws Exception {
		HttpPost post = new HttpPost(url);
		post.setConfig(POST_REQUEST_CONFIG);

		MultipartEntityBuilder builder = MultipartEntityBuilder.create();

		if (null != params) {
			for (String key : params.keySet()) {
				builder.addPart(key, new StringBody(params.get(key), ContentType.TEXT_PLAIN));
			}
		}

		if (null != fileList) {
			for (File file : fileList) {
				builder.addPart("files", new FileBody(file));
			}
		}

		HttpEntity entity = builder.build();
		post.setEntity(entity);
		return execute(post);
	}

//	public static String post(String url, InputStream inputStream) throws Exception {
//		HttpPost post = new HttpPost(url);
//		post.setConfig(POST_REQUEST_CONFIG);
//
//  
//        
//		return execute(post);
//	}

	/**
	 * 发送HTTP请求
	 * 
	 * @param request HttpUriRequest实体
	 * @return 返回的内容
	 * @throws Exception
	 */
	public static String execute(HttpUriRequest request) throws Exception {
		String content = null;

		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;

		try {
			client = HttpClients.createDefault();
			response = client.execute(request);
			HttpEntity entity = response.getEntity();
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				content = EntityUtils.toString(entity, "UTF-8");
			} else {
				LOGGER.info("statusCode:", statusCode);
				LOGGER.info("content:", EntityUtils.toString(entity, "UTF-8"));
			}
		} catch (Exception e) {
			LOGGER.error("发送HTTP请求错误！", e);
			throw e;
		} finally {
		}
		return content;
	}

}
